package com.yanx.common.security.service;

import com.yanx.common.constant.CacheConstants;
import com.yanx.common.exception.user.UserPasswordRetryLimitExceedException;
import com.yanx.common.security.LoginInforRecordUtils;
import com.yanx.common.utils.Message_;
import com.yanx.framework.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 *
 * @author ruoyi
 */
@Component
public class PasswordService {
    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount:5}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime:5}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validateRetry(String username) {
        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            LoginInforRecordUtils.error(username, Message_.message("user.password.retry.limit.exceed", maxRetryCount, lockTime));
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }
    }


    public void increaseRetry(String username) {
        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
        if (retryCount == null) {
            retryCount = 0;
        }
        retryCount += 1;
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
//                    MessageUtils.message("user.password.retry.limit.count", retryCount)));
        LoginInforRecordUtils.error(username, Message_.message("user.password.retry.limit.count", retryCount));
        redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
    }

    public void cleanRetry(String username) {
        redisCache.deleteObject(getCacheKey(username));
    }

}
